from django.http import JsonResponse, HttpResponseRedirect
from django.shortcuts import redirect, render
from django.views.decorators.csrf import csrf_exempt

from restaurant.models import Comment
from user.models import UserInfo
from restaurant.models import Order


def to_comments(request, user_id, order_id):
    user = UserInfo.objects.get(id=user_id)
    my_order = Order.objects.get(order_id=order_id)
    my_comment = Comment.objects.filter(order_id=order_id, user_id=user_id)
    request.session["user"] = {'id': user.id, 'name': user.username}
    request.session["my_order"] = {'order_id': my_order.order_id, 'content': my_order.content, 'total': float(my_order.total),
                                   'comment': my_order.comment}
    return render(request, 'user/comments.html', {'user': user, 'my_order': my_order, 'comment_list': my_comment})


def total_comments():
    return redirect('/restaurant/total_comments')


@csrf_exempt
def post_comment(request):
    user = request.session.get('user')
    my_order = request.session.get('my_order')
    user_id = user['id']
    order_id = my_order['order_id']
    user_name = user['name']
    comment_text = request.POST.get('comment', '')
    order_content = my_order['content']
    order_total = my_order['total']
    order_comment = my_order['comment']
    comment = Comment(
        text=comment_text,
        user_id=user_id,
        order_id=order_id,
        user_name=user_name,
        content=order_content,
        total_price=order_total,
        comment=order_comment
    )
    comment.save()
    return render(request, 'user/comments.html')


@csrf_exempt
def delete_comment(request, comment_id):
    try:
        de_comment = Comment.objects.get(id=comment_id)
        de_comment.delete()
        return JsonResponse({'success': True, 'message': '评论删除成功'})
    except Comment.DoesNotExist:
        return JsonResponse({'success': False, 'message': '评论不存在'})
    except Exception as e:
        return JsonResponse({'success': False, 'message': str(e)})